package com.example.androidlearning2200;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CameraActivity extends AppCompatActivity {

    private ImageView imgAvatar;
    private ActivityResultLauncher launcherCamera;
    private ActivityResultLauncher launcherAlbum;
    private File outputImage;
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        imgAvatar = findViewById(R.id.imgAvatar);
        launcherCamera = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    imgAvatar.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        launcherAlbum = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                try {
                    Uri uri = result.getData().getData();
                    ParcelFileDescriptor fileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
                    Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor());
                    imgAvatar.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        findViewById(R.id.btnCamera).setOnClickListener(view -> takePhoto());
        findViewById(R.id.btnAlbum).setOnClickListener(view -> openAlbum());
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        launcherAlbum.launch(intent);
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        // 新建文件，存储相机拍摄的照片
        // 通过目录和文件名创建文件
        try {
            outputImage = new File(getExternalCacheDir(), "sxt" + System.currentTimeMillis());
            outputImage.createNewFile();
            imageUri = FileProvider.getUriForFile(this, "com.example.androidlearning2200.fileprovider", outputImage);
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            launcherCamera.launch(intent);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}